package com.ruoyi.material.rpc.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.material.domain.VimsTask;
import com.ruoyi.material.domain.constant.VIMSApiConstant;
import com.ruoyi.material.domain.vo.TradeTreeVO;
import com.ruoyi.material.domain.vo.VimsTaskVo;
import com.ruoyi.material.rpc.IVIMSTaskService;
import com.ruoyi.material.util.HttpClients;
import com.ruoyi.material.util.VIMSTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: MSS
 * @description: 远程表用VIMS的接口
 * @author: cyw
 * @create: 2021-08-02 16:22
 **/
@Service
public class VIMSTaskServiceImpl implements IVIMSTaskService {
    private Logger logger = LoggerFactory.getLogger(VIMSTaskServiceImpl.class);
    @Autowired
    private VIMSTokenService vimsTokenService;

    @Override
    public VimsTask selectVimsTaskById(String schedulename) {
        return null;
    }

    @Override
    public String selectVimsTaskList(VimsTaskVo vimsTask) {
        String token = null;
        try {
            token = vimsTokenService.getToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        vimsTask.setToken(token);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        vimsTask.setPageNumber(pageDomain.getPageNum());
        vimsTask.setPagesize( pageDomain.getPageSize());
        String params = vimsTask.transferParams();
        String resp  = HttpUtils.sendGet(VIMSApiConstant.IP+VIMSApiConstant.ListScreenshotTimingTask,params);
        logger.info("===list() 获取的token{} ===",token);
        logger.info("===list() 获取的请求参数{} json{} ===",vimsTask,params);
        logger.info("===list() 请求结果{} ===",resp);
        return resp ;
    }



    @Override
    public int updateVimsTask(VimsTask vimsTask) {
        return 0;
    }

    @Override
    public String deleteVimsTaskByIds(String[] ids) {
        if (ids == null || ids.length <=0){
            return AjaxResult.error("未选择要删除的任务，请重新选择").toString();
        }
        String token = "";
        try {
            token = vimsTokenService.getToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = VIMSApiConstant.IP + VIMSApiConstant.DeleteScreenshotTimingTask;
        String params = "token="+token;
        for (int i=0;i<ids.length;i++){
            params += "&scheduleId="+ids[i];
        }
        logger.info("deleteVimsTaskByIds() ==={} ===",url);
        logger.info("deleteVimsTaskByIds() ==={} ===",params);
        String resp = HttpUtils.sendGet(url,params);
        logger.info("deleteVimsTaskByIds() ==={} ===",resp);
        return resp;
    }

    @Override
    public int deleteVimsTaskById(String schedulename) {
        return 0;
    }

    /**
     * 通道树
     */
    public String getChannelTree(){
        String token = null;
        try {
            token = vimsTokenService.getToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("===VIMSTaskServiceImpl====getChannelTree()===获取Token [{}]",token);
        if (token == null){
            return AjaxResult.error("请求失败，无法获取token").toString();
        }
        logger.info("===VIMSTaskServiceImpl====getChannelTree()===获取Token [{}]",token);
        String params = "token="+token;
        String resp = HttpUtils.sendGet(VIMSApiConstant.IP+VIMSApiConstant.QueryChannelTree,params);
        List<TradeTreeVO> treeList = JSON.parseArray(resp,TradeTreeVO.class);
        DFSTradeTreeVO(treeList);
        return  JSONObject.toJSONString(treeList);

    }
    //处理通道树去除空节点
    public void DFSTradeTreeVO( List<TradeTreeVO> treeList){

        for (int i=0;i<treeList.size();i++){
           DFS(treeList.get(i));
        }
    }

    /**
     * 判断是否合法
     * @param vo
     * @return
     */
    public  TradeTreeVO DFS(TradeTreeVO vo){
        if (vo.getChildren() == null &&vo.getChannelCode() != null){
            return vo;
        }
        if (vo.getChildren() == null &&vo.getChannelCode() == null){
            return null;
        }

        for (int i=0;i<vo.getChildren().size();i++){
            TradeTreeVO children = DFS(vo.getChildren().get(i));
            if (children == null){
                vo.getChildren().remove(i);
                i--;
            }
        }
        // 筛选处理后
        if (vo.getChildren() == null || vo.getChildren().size() == 0){
            return  null;
        }
        return vo;
    }
    public void DFSTradeTreeVO( List<TradeTreeVO> cRoot,TradeTreeVO root) {
        if (root == null || cRoot == null ){
            return;
        }
        if (root.getType() == "ORGANIZATION") {
            List<TradeTreeVO> deviceList = root.getChildren();
            for (int i=0;i<deviceList.size();i++){
                List<TradeTreeVO>  channelList = deviceList.get(i).getChildren();
                for (int j=0;j<channelList.size();j++){
                    if (channelList.get(j).getChannelCode() == null || channelList.get(j).getChannelCode() == ""){
                        logger.info("DFSTradeTreeVO  移除对象 [{}]" ,channelList.get(j));
                        root.getChildren().get(i).getChildren().remove(j);
                    }
                }
            }
            return;
        }
        for (int i=0;i<cRoot.size();i++){
            DFSTradeTreeVO(cRoot.get(i).getChildren(),cRoot.get(i));
        }

    }

    public String getPresetPoint(List<String> channelCodes){
        String token = "";
        try {
             token = vimsTokenService.getToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String params = "";
        for (int i=0;i<channelCodes.size();i++){
            params += "channelCodes="+channelCodes.get(i)+"&";
        }
        params += "token=" + token;
        logger.info("=== getPresetPoint === 请求参数 {}" ,params);
        String resp = HttpUtils.sendPost(VIMSApiConstant.IP+VIMSApiConstant.ListOfPresetPoints,params);
        JSONObject jsonObject = JSONObject.parseObject(resp);
        if (jsonObject.get("msg")!= null && jsonObject.get("msg").equals("未获取到有效token")){
            try {
                token = vimsTokenService.getReToken();
                params = params.substring(0,params.lastIndexOf("token"));
                params += "token=" +token;
                logger.info("===重新请求参数=== {}",params);
                return HttpUtils.sendPost(VIMSApiConstant.IP+VIMSApiConstant.ListOfPresetPoints,params);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        logger.info("=== getPresetPoint === 请求结果 {}" ,resp);
        return  resp;
    }

    @Override
    public String insertVimsTask(VimsTaskVo vimsTask) {
        String token = "";
        try {
            token = vimsTokenService.getToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        vimsTask.setToken(token);
        String url = VIMSApiConstant.IP+VIMSApiConstant.AddScreenshotTimingTask+"?token="+token;
        String params = vimsTask.transferParams();

        logger.info("===insertVimsTask() params=== {}" ,JSONObject.toJSONString(vimsTask));
        logger.info("===insertVimsTask() url=== {}" ,url);
        String resp = "";
        resp = HttpClients.sendPost(JSONObject.toJSONString(vimsTask),url);

        logger.info("请求结果 == {}",resp);
        return resp;
    }

    public String stopVimsTaskByIds(String id){
        if (id == null){
            return AjaxResult.error("未选中停止的任务，请选择").toString();
        }
        String token = "";
        try {
            token = vimsTokenService.getToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = VIMSApiConstant.IP+VIMSApiConstant.StopScreenshotTimingTask;
        String params ="token=" +token +"&scheduleId="+id;
        logger.info("stopVimsTaskByIds=== params{}  url{}",params,url);
        return HttpUtils.sendGet(url,params);
    }
}
